<!-- 配送商端 - 新建订单 - 新建手术跟台需求订单 -->
<template>
  <div class="add-order-box">
    <el-container class="container-box">
      <div
        height="auto"
        class="header-box width-limit-box">
        <h3 class="header-title">基础信息</h3>
        <el-form-renderer
          label-width="140px"
          :content="formContent"
          ref="operationForm"
          class="form-box"
        />
      </div>
      <el-header>
        <h3 class="container-title">产品信息</h3>
      </el-header>

      <div
        class="top-add-button-wrapper"
        v-if="!isEmptyList">
        <div class="btn-box">
          <el-button
            type="text"
            class="add-btn"
            @click="handleAddDialog">添加产品</el-button>
            <!--目前未实现此功能所以先隐藏-->
            <!-- <el-button
            type="text"
            class="add-btn"
            @click="handleImportProduct">
            导入产品
          </el-button>
          <el-button
            type="text"
            class="add-btn"
            @click="handleDownloadTemplate">
            下载导入模板.cvs
          </el-button>-->
        </div>
        <p class="order-total-amount">总计：{{ orderTotalAmount() | getFormatterPrice }}</p>
      </div>
      <el-editable
        v-if="!isEmptyList"
        :custom-attr="$TABLE_HEAD['beforeSettle.distributorSide.newOrder.operationOrder']"
        :data="tableData"
        :columns="operationListColumns"
        height="400"
      >
        <template
          slot="default-purchaseNum"
          slot-scope="scope">
          <el-input-number
            class="num-box"
            @change="resetIllegalInput(scope.row,$event)"
            v-model="scope.row.count"
            step-strictly
            size="mini"
            :min="1"
            :max="10e6"
          />
        </template>
        <template
          slot="default-detailAmount"
          slot-scope="scope">
          <span>11</span>
        </template>
        <template
          slot="default-action"
          slot-scope="scope">
          <el-button
            size="small"
            @click.stop="deleteOrderProductItem(scope)"
            type="text text-danger"
          >删除</el-button>
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <!-- <el-pagination
        v-if="!isEmptyList"
        class="pagination"
        align="right"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="totalElements"
      /> -->
      <!-- 中间添加产品按钮 -->
      <div
        class="center-add-button-wrapper"
        v-if="isEmptyList">
        <el-button
          type="primary"
          @click="handleAddDialog">+ 添加产品</el-button>
          <!--目前未实现此功能所以先隐藏-->
          <!-- <div class="import-download-box">
          <el-button
            type="primary"
            class="import-btn"
            @click="handleImportProduct">
            + 导入产品
          </el-button>
          <el-button
            type="text"
            class="add-btn"
            @click="handleDownloadTemplate">
            下载导入模板.cvs
          </el-button>
        </div>-->
      </div>
    </el-container>
    <add-product-dialog
      :dialog-visible.sync="productDialogVisible"
      :query-url="authItemSaleOrderQuery"
      query-method="post"
      :extra-query="pCompanyQuery"
      :current-products="saleOrderProductList"
      @confirmDialog="addSelectionToProductList"
      @cancelDialog="cancelAddSelection"
    />
  </div>
</template>
<script>
import { mapMutations, mapState } from 'vuex'
import ElEditable from '@components/el-editable/index.vue'
import AddProductDialog from '@/moduleComponents/beforeSettle/distributorSide/addProduct'

import { isObject, cloneDeep } from 'lodash'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common.js'
import { formContent, operationListColumns } from './const.js'
import { getFormatterPrice, computeRate } from '@const/filter'

import {
  authItemSaleQuery,
  hospitalList,
  createOrder
} from '@const/beforeSettleApi'
import { authItemSaleOrderQuery } from '@const/productCenterApiV2'
export default {
  name: 'OperationList',
  components: { ElEditable, AddProductDialog },
  data () {
    const _this = this
    return {
      // form表单信息

      authItemSaleOrderQuery,
      selectListloading: false,
      hospitalNameList: [],
      currentFormValue: {},
      formContent: [
        {
          $type: 'select',
          $id: 'hospitalId',
          label: '请选择寄售医院',
          $el: {
            placeholder: '请输入',
            filterable: true,
            remote: true,
            loading: _this.selectListloading,
            async 'remote-method' (query) {
              const companyName = query.trim()
              if (companyName !== '') {
                try {
                  _this.selectListloading = true
                  const { payload } = await _this.$axios.$get(hospitalList, {
                    params: { companyName, companyType: 'HO' }
                  })
                  _this.hospitalNameList = payload || []
                  if (!payload.length) return
                  const options = payload.map(({ id, fullName }) => ({
                    value: id,
                    label: fullName
                  }))
                  _this.$refs['operationForm'].setOptions('hospitalId', options)
                } catch (err) {
                  console.error()
                } finally {
                  _this.selectListloading = false
                }
              }
            }
          },
          $options: [],
          rules: [{ required: true, message: '请选择', trigger: 'change' }]
        },
        ...formContent
      ],
      operationListColumns,
      // 产品弹窗信息
      productDialogVisible: false,
      saleOrderProductList: [],
      authItemSaleQuery,

      curPage: 1,
      totalElements: 1,
      PAGE_NUMBER,
      PAGINATION_LAYOUT,
      pageSize: PAGE_NUMBER[0]
    }
  },
  filters: {
    getFormatterPrice
  },
  computed: {
    ...mapState(['companyId']),

    pCompanyQuery () {
      return {
        upEnterpriseId: this.companyId,
        enterpriseId: this.currentFormValue.hospitalId
      }
    },

    isEmptyList () {
      return this.saleOrderProductList.length === 0
    },
    hasEmptyOrderNum () {
      return this.saleOrderProductList.some(item => !item.purchaseNum)
    },
    tableData () {
      const startIndex = this.pageSize * (this.curPage - 1)
      const endIndex = startIndex + this.pageSize
      return this.saleOrderProductList.slice(startIndex, endIndex)
    }
  },
  mounted () {
    this.initNavButtons()
  },
  methods: {
    ...mapMutations(['changeLayoutHandle']),
    orderTotalAmount () {
      // return this.saleOrderProductList.reduce((pre, cur) => {
      //   return cur.price === null
      //     ? 0
      //     : pre + computeRate(cur.price, cur.purchaseNum)
      // }, 0)
      let amount = 0
      this.saleOrderProductList.forEach(item => {
        // if (item.count) {
        //   amount = computeAdd(
        //     amount,
        //     computeRate(item.count, item.buyPrice)
        //   )
        //   console.log(amount)
        // }
        if (item.count) {
          amount += item.count * item.price
        }
      })
      return amount
    },
    // 初始化 导航栏 按钮组
    initNavButtons () {
      const btn = {
        type: 'btn',
        arr: [{ type: 'primary', val: '提交', handle: this.handleNavBtnSubmit }]
      }
      this.changeLayoutHandle(btn)
    },
    handleNavBtnSubmit () {
      const formValue = this.$refs.operationForm.getFormValue()
      const hospitalNameInfo =
        this.hospitalNameList.find(it => it.id === formValue.hospitalId) || {}
      this.tableData.forEach(item => {
        item.purchaseNum = item.count
      })
      const params = {
        ...formValue,
        orderType: 2, // 标识订单来源 1.寄售创建 2.跟台创建
        hospitalName: hospitalNameInfo.fullName || '',
        items: [...this.tableData]
      }
      this.$refs['operationForm'].validate(valid => {
        if (!valid) return
        if (this.saleOrderProductList.length < 0) return
        if (this.hasEmptyOrderNum) {
          return this.$message.warning('订单数量不能为空')
        }
        this.$confirm('确认要提交吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success',
          beforeClose: (action, instance, done) => {
            if (action !== 'confirm') return done()
            instance.confirmButtonLoading = true
            this.$axios
              .post(createOrder, params)
              .then(({ data }) => {
                if (Number(data.code) !== 0) return
                done()
                this.$message.success('提交成功')
                this.$router.push({
                  path:
                    '/distributorSide/salesManagement/operationOrder'
                })
              })
              .finally(() => {
                instance.confirmButtonLoading = false
              })
          }
        }).catch(e => {})
      })
    },
    handleAddDialog () {
      this.currentFormValue = this.$refs.operationForm.getFormValue()
      if (!this.currentFormValue.hospitalId) {
        return this.$message.warning('请先选择寄售医院')
      }
      this.productDialogVisible = true
    },
    cancelAddSelection () {
      this.productDialogVisible = false
    },
    addSelectionToProductList (selection) {
      // 如果选择项中已经添加过了，就按最新的数量更新, 未添加过就格式化一下字段添加
      selection.forEach(item => {
        const addedItem = this.saleOrderProductList.find(
          addedItem => addedItem.id === item.id
        )
        if (addedItem) {
          addedItem.purchaseNum = item.purchaseNum
          this.saleOrderProductList.forEach((its, index) => {
            if (addedItem.id === its.id) {
              its.count++
            }
          })
        } else {
          item.count = item.purchaseNum
          this.saleOrderProductList.push({
            ...item,
            ...this.formatSelectedData(item)
          })
        }
      })
      this.productDialogVisible = false
    },
    formatSelectedData (item) {
      return {
        deliveryProductCode: '', // 配送商产品编码
        deliveryProductName: '', // 配送商产品名称
        provinceProductCode: '', // 省平台编码
        manageCategory: item.managerType, // 管理分类 1 一类 2 二类 3 三类
        category: item.productCategory, // 产品大类 1高值 2低值 3试剂 4设备 5器械
        authProdId: item.id,
        registerType: item.registerArea // 1国产 2港澳台 3进口
      }
    },
    resetIllegalInput (row, value) {
      if (value % 1 !== 0) {
        row.count = Math.round(value)
      }
      this.orderTotalAmount()
    },
    handleImportProduct () {
      // TODO导入产品
    },
    handleDownloadTemplate () {
      // TODO下载模板
    },
    deleteOrderProductItem (scope) {
      this.saleOrderProductList.splice(scope.$index, 1)
    },
    handleSizeChange (size) {
      this.pageSize = size
    },
    handleCurrentChange (page) {
      this.curPage = page
    }
  }
}
</script>
<style lang="less">
@import '../m-front-common/pc/assets/var.less';
@textColor: #26344c;
@borderColor: #eef0f5;
@bgColor: #f7f8fa;
@btnColor: #2371c5;
@white: #fff;
.title-common-style() {
  color: @textColor;
  padding: 0 0 12px 20px;
  border-bottom: 1px solid @borderColor;
}

.add-order-box {
  .header-box {
    padding-top: 10px;
    border-bottom: 8px solid @bgColor;

    .header-title {
      .title-common-style();
    }

    .form-box {
      padding: 16px;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;

      .el-form-item {
        width: 33.33%;
      }
    }
  }

  .container-box {
    height: 100%;
    overflow: auto;

    .container-title {
      .title-common-style();

      width: 100%;
      padding-top: 12px;
    }

    .top-add-button-wrapper {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      padding: 24px 0;

      .add-btn {
        padding-left: 32px;
      }

      .order-total-amount {
        font-size: 20px;
        font-weight: 500;
      }
    }

    .center-add-button-wrapper {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      padding-top: 120px;

      .import-download-box {
        padding-top: 16px;

        .import-btn {
          margin-left: 126px;
        }

        .el-button--primary {
          color: @btnColor;
          background-color: @white;
        }
      }
    }

    .pagination {
      padding-top: 20px;
    }
  }
  .width-limit-box {
    .el-input .el-input--medium,
    .el-input__inner {
      width: 230px;
    }
  }
}
</style>
